package com.x.erp.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.x.erp.model.InsuranceGoods;
import com.x.erp.model.InsuranceOrder;
import com.x.erp.model.InsuranceOrderGoods;
import com.x.erp.rpc.InsuranceGoodsRpcService;
import com.x.erp.rpc.InsuranceOrderRpcService;
import com.x.erp.util.ConstantState;
import com.x.framework.controller.BaseController;
import com.x.framework.controller.ResultCode;
import com.x.framework.controller.ResultModel;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 延保商品订单Controller
 *
 * @author pansong
 */
@RestController
@RequestMapping(value = "/insuranceOrder")
public class InsuranceOrderController extends BaseController {

	@Reference
	private InsuranceOrderRpcService insuranceOrderRpcService; // 延保商品订单服务

	@Reference
	private InsuranceGoodsRpcService insuranceGoodsRpcService; // 延保商品服务

	/**
	 * 获取延保商品订单列表
	 *
	 * @param insuranceOrder
	 * @return
	 */
	@RequestMapping(value = "/selectInsuranceOrderList", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel selectInsuranceOrderList(InsuranceOrder insuranceOrder) {
		List<InsuranceOrder> list = insuranceOrderRpcService.selectInsuranceOrderList(insuranceOrder);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", list);
	}

	/**
	 * 获取延保商品订单数量
	 *
	 * @param insuranceOrder
	 * @return
	 */
	@RequestMapping(value = "/selectInsuranceOrderNum", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel selectInsuranceOrderNum(InsuranceOrder insuranceOrder) {
		int res = insuranceOrderRpcService.selectInsuranceOrderNum(insuranceOrder);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", res);
	}

	/**
	 * 获取延保商品订单(帶合同信息)
	 *
	 * @param insuranceOrder
	 * @return
	 */
	@RequestMapping(value = "/selectInsuranceOrder", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel selectInsuranceOrder(InsuranceOrder insuranceOrder) {
		if(StringUtils.isEmpty(insuranceOrder.getOrderId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "订单Id不能为空");
		}
		InsuranceOrder temp = insuranceOrderRpcService.selectInsuranceOrder(insuranceOrder);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", temp);
	}

	/**
	 * 新增延保商品订单
	 *
	 * @param insuranceOrder
	 * @return
	 */
	@RequestMapping(value = "/insertInsuranceOrder", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel insertInsuranceOrder(InsuranceOrder insuranceOrder, String orderGoodsJson) {
		if (StringUtils.isEmpty(insuranceOrder.getUserId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户Id不用为空");
		}
		List<InsuranceOrderGoods> orderGoodsList = JSON.parseArray(orderGoodsJson, InsuranceOrderGoods.class);
		if (orderGoodsList == null || orderGoodsList.size() == 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "延保商品信息不能为空");
		}
		// 获取商品列表价格信息
		Map<String, String> goodsPriceMap = getGoodsPriceMap();
		// 判断订单商品单价和计算订单总价
		Iterator<InsuranceOrderGoods> its = orderGoodsList.iterator();
		BigDecimal orderPrice = new BigDecimal(0);
		while(its.hasNext()){
			InsuranceOrderGoods orderGoodsTemp = its.next();
			Integer orderGoodsNum = orderGoodsTemp.getOrderGoodsNum();
			if(orderGoodsNum == null || orderGoodsNum == 0){// 如果数量为null或者0，从集合中移除，不存储到数据库
				its.remove();
				continue;
			}
			if(orderGoodsNum < 0 || orderGoodsNum >= 10000){
				return new ResultModel(ResultCode.RESULT_FAIL, "商品数量不能为空、小于0、大于等于1万");
			}
			if(StringUtils.isEmpty(orderGoodsTemp.getGoodsId())){
				return new ResultModel(ResultCode.RESULT_FAIL, "商品Id不能为空");
			}
			if(StringUtils.isEmpty(orderGoodsTemp.getGoodsName())){
				return new ResultModel(ResultCode.RESULT_FAIL, "商品名称不能为空");
			}
			// 为订单商品赋值单价，并检测商品Id是否正确
			if(!createOrderGoodUnitPrice(orderGoodsTemp, goodsPriceMap)){
				return new ResultModel(ResultCode.RESULT_FAIL, "商品Id不正确");
			}
			// 计算订单总价
			orderPrice = orderPrice.add(orderGoodsTemp.getOrderGoodsUnitPrice().multiply(new BigDecimal(orderGoodsNum)));
		}
		// 将订单总价存入订单信息
		insuranceOrder.setOrderPrice(orderPrice);
		// 将商品数据存入订单里
		insuranceOrder.setOrderGoodsList(orderGoodsList);
		// 订单状态处于待审核状态
		insuranceOrder.setOrderState(ConstantState.INSURANCE_ORDER_STATE_INITIAL);
		InsuranceOrder temp = insuranceOrderRpcService.insertInsuranceOrder(insuranceOrder);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "新增成功", temp);
	}

	// 为订单商品赋值单价
	private boolean createOrderGoodUnitPrice(InsuranceOrderGoods orderGoodsTemp, Map<String, String> goodsPriceMap) {
		String priceDesc = goodsPriceMap.get(orderGoodsTemp.getGoodsId());// 如：[{"num":50,"price":419},{"num":30,"price":499},{"num":10,"price":549},{"num":0,"price":599}]
		if(StringUtils.isEmpty(priceDesc)){
			return false;
		}
		JSONArray pd = JSONObject.parseArray(priceDesc);
		Integer orderGoodsNum = orderGoodsTemp.getOrderGoodsNum();
		JSONObject jObj = null;
		Integer num = null;
		BigDecimal price = null;
		for(int i = 0;i < pd.size();i++){
			jObj = pd.getJSONObject(i);
			num = new Integer(jObj.getString("num"));
			price = new BigDecimal(jObj.getString("price"));
			if(orderGoodsNum >= num){
				orderGoodsTemp.setOrderGoodsUnitPrice(price);
				return true;
			}
		}
		return false;
	}

	private Map<String, String> getGoodsPriceMap() {
		// 获取商品列表价格信息
		List<InsuranceGoods> goodsList = insuranceGoodsRpcService.selectInsuranceGoodsList(new InsuranceGoods());
		Map<String, String> goodsPriceMap = new HashMap<>();
		for (InsuranceGoods goods : goodsList){
			goodsPriceMap.put(goods.getGoodsId(),goods.getGoodsPriceDesc());
		}
		return goodsPriceMap;
	}

	/**
	 * 删除延保商品订单
	 *
	 * @param insuranceOrder
	 * @return
	 */
//	@RequestMapping(value = "/deleteInsuranceOrder", method = {RequestMethod.POST, RequestMethod.GET})
//	public ResultModel deleteInsuranceOrder(InsuranceOrder insuranceOrder) {
//		int temp = insuranceOrderRpcService.deleteInsuranceOrder(insuranceOrder);
//		if (temp > 0) {
//			return new ResultModel(ResultCode.RESULT_SUCCESS, "删除成功", temp);
//		} else {
//			return new ResultModel(ResultCode.RESULT_FAIL, "删除失败", temp);
//		}
//	}

	/**
	 * 修改延保商品订单
	 *
	 * @param insuranceOrder
	 * @return
	 */
	@RequestMapping(value = "/updateInsuranceOrder", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel updateInsuranceOrder(InsuranceOrder insuranceOrder) {
		if (StringUtils.isEmpty(insuranceOrder.getOrderId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "订单Id不能为空");
		}
		if (insuranceOrder.getOrderState() == null ) {
			return new ResultModel(ResultCode.RESULT_FAIL, "订单状态不正确");
		}
		if (!(insuranceOrder.getOrderState() == ConstantState.INSURANCE_ORDER_STATE_USING || insuranceOrder.getOrderState() == ConstantState.INSURANCE_ORDER_STATE_EXPIRED)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "订单状态不正确");
		}
		if(insuranceOrder.getOrderState() == ConstantState.INSURANCE_ORDER_STATE_EXPIRED){
			if(StringUtils.isEmpty(insuranceOrder.getOrderNgContent())){
				return new ResultModel(ResultCode.RESULT_FAIL, "订单拒绝原因不能为空");
			}
		}
		int temp = insuranceOrderRpcService.updateInsuranceOrder(insuranceOrder);
		if (temp > 0) {
			return new ResultModel(ResultCode.RESULT_SUCCESS, "修改成功");
		} else {
			return new ResultModel(ResultCode.RESULT_FAIL, "修改失败");
		}
	}
}
